package com.zzyl.framework.interceptor;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpStatus;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户端请求拦截器
 *
 * @Author mr.zhang
 * Date 2025/5/25 9:40
 */
@Component
public class MemberInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断请求类型
        if (!(handler instanceof HandlerInterceptor)){
            return true;
        }
        //2.获取token
        String token = request.getHeader("authorization");

        //3.判断是否为空
        if (StringUtils.isBlank(token)){
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new RuntimeException("token为空");
        }
        //4.解析token
        try {
            //5.判断解析是否正确
            Claims claims = tokenService.parseToken(token);

            Long userId = Long.valueOf(claims.get("userId").toString());

            UserThreadLocal.set(userId);

        } catch (Exception e) {
            e.printStackTrace();
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            throw new RuntimeException("解析token失败");
        }
        //6.放行
        return true;
    }



    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
